public class AddMonthlyNewBornControl{
    public List<AddMonthlyNewBornItemControl> RecordList{
        get;
        set;
    }
    public List<Hospital__c> HospitalList{get;set;}
    public String msg{get;set;}
    public String msg1{get;set;}
    public Boolean Overdate{get;set;}
    public Boolean SaveOrNot{get;set;}
    public Boolean dateErrorYear{get;set;}
    public Boolean dateErrorMon{get;set;}
    public String yearSelect{get;set;}
    public String monthSelect{get;set;}
    public List<SelectOption> YearList
    {
        get
        {
            if(YearList== null)
                YearList= new List<SelectOption>();
            else
                YearList.clear();
            YearList.add(new SelectOption('0','无'));
            YearList.add(new SelectOption('1','2010'));
            YearList.add(new SelectOption('2','2011'));
            YearList.add(new SelectOption('3','2012'));
            YearList.add(new SelectOption('4','2013'));
            YearList.add(new SelectOption('5','2014'));
            YearList.add(new SelectOption('6','2015'));
            YearList.add(new SelectOption('7','2016')); 
            
            return YearList;                      
        }
        set;
    }
    public List<SelectOption> MonthList
    {
        get
        {
            if(MonthList== null)
                MonthList= new List<SelectOption>();
            else
                MonthList.clear();
            
            if(yearSelect != null){
                MonthList.add(new SelectOption('0','无'));
                MonthList.add(new SelectOption('1','1'));
                MonthList.add(new SelectOption('2','2'));
                MonthList.add(new SelectOption('3','3'));
                MonthList.add(new SelectOption('4','4'));
                MonthList.add(new SelectOption('5','5'));
                MonthList.add(new SelectOption('6','6'));
                MonthList.add(new SelectOption('7','7')); 
                MonthList.add(new SelectOption('8','8'));
                MonthList.add(new SelectOption('9','9'));
                MonthList.add(new SelectOption('10','10'));
                MonthList.add(new SelectOption('11','11'));
                MonthList.add(new SelectOption('12','12'));
            }
            else{
                MonthList.add(new SelectOption('0','无'));
            }
                        
            return MonthList;                      
        }
        set;
    }

    
    public String UrlId
    {
        get{
            return System.currentPageReference().getParameters().get('id');
        }
        set;
    }
    
    public Integer IyearCom;
    public  Integer Imonth;
    
    public PageReference actionSupport(){
        Overdate = false;
        dateErrorYear = false;
        dateErrorMon  = false;
        if(SaveOrNot == false){
            msg1 = null;  
        }
        
        if(RecordList==null)
            RecordList=new List<AddMonthlyNewBornItemControl>();
        else     
            RecordList.clear();

            HospitalList = new List<Hospital__c> ();

            date DtodayCom = date.today();
            
            if(yearSelect == '1'){
                IyearCom = 2010;
                dateErrorYear = true;
            }
            if(yearSelect == '2'){
                IyearCom = 2011;
                dateErrorYear = true;
            }            
            if(yearSelect == '3'){
                IyearCom = 2012;
                dateErrorYear = true;
            }
            if(yearSelect == '4'){
                IyearCom = 2013;
                dateErrorYear = true;
            }             
            if(yearSelect == '5'){
                IyearCom = 2014;
                dateErrorYear = true;
            }
            if(yearSelect == '6'){
                IyearCom = 2015;
                dateErrorYear = true;
            }  
            if(yearSelect == '7'){
                IyearCom = 2016;
                dateErrorYear = true;
            }  
            
            if(monthSelect == '1'){
                Imonth = 1;
                dateErrorMon  = true;
            }
            if(monthSelect == '2'){
                Imonth = 2;
                dateErrorMon  = true;
            }
            if(monthSelect == '3'){
                Imonth = 3;
                dateErrorMon  = true;
            }
            if(monthSelect == '4'){
                Imonth = 4;
                dateErrorMon  = true;
            }            
            if(monthSelect == '5'){
                Imonth = 5;
                dateErrorMon  = true;
            }
            if(monthSelect == '6'){
                Imonth = 6;
                dateErrorMon  = true;
            }
            if(monthSelect == '7'){
                Imonth = 7;
                dateErrorMon  = true;
            }
            if(monthSelect == '8'){
                Imonth = 8;
                dateErrorMon  = true;
            }              
            if(monthSelect == '9'){
                Imonth = 9;
                dateErrorMon  = true;
            }
            if(monthSelect == '10'){
                Imonth = 10;
                dateErrorMon  = true;
            }
            if(monthSelect == '11'){
                Imonth = 11;
                dateErrorMon  = true;
            }
            if(monthSelect == '12'){
                Imonth = 12;
                dateErrorMon  = true;
            }
            if(monthSelect == '0'){
                msg = null;
                return null;
            }
            if((dateErrorYear == false)||(dateErrorMon  = false)){
                msg = null;
                return null;          
            }
            if((IyearCom > date.today().year())||((IyearCom == date.today().year())&&(Imonth >= date.today().month()))){
                msg = '不能记录本月及以后的出生数';
                Overdate = true;
                return null;
            }
            else{
                msg = null;
            }                                    

            Integer Iyear = IyearCom;
            String Smonth = String.valueOf(Imonth);
            String Syear = String.valueOf(Iyear);

            List<Hospital__c> MyHosptialList = [Select Id,Name,Active__c,class__c,effectivedate__c,approvaltype__c,lastvisiteddate__c From
                Hospital__c where OwnerId  =: UserInfo.getUserId()];
            List<Id> MyHospitalId = new List<Id>();
            for(Hospital__c h : MyHosptialList)
            {
                MyHospitalId.add(h.Id);
                
            }
            
            List<NewBornNumber__c> haveRecordList = [select Id,hospital_class__c,ownerid,Hospital__c,Hospital__r.name,Name,Month__c,Year__c,NewBornNum__c,
                                   HospitalClass__c from NewBornNumber__c where  ((Hospital__c in: MyHospitalId) or (ownerid =: UserInfo.getUserId())) and 
                                   Year__c =: Syear and Month__c =: Smonth]; // get this month's new born record

            List<NewBornNumber__c> AllhaveRecordList = [select Id,hospital_class__c,Hospital__c,Hospital__r.name,Name,Month__c,Year__c,NewBornNum__c,
                                   HospitalClass__c from NewBornNumber__c where 
                                   Year__c =: Syear and Month__c =: Smonth and Hospital__c in: MyHospitalId]; // get this month's new born record

            List<Id> ExistNewBornHosId = new List<Id>();
            for(NewBornNumber__c n : AllhaveRecordList)
            {
                ExistNewBornHosId.add(n.Hospital__c);
                
            }
            List<Hospital__c> HosptialListAll = [Select Id,Name,Active__c,class__c,effectivedate__c,approvaltype__c,lastvisiteddate__c From
                Hospital__c where OwnerId  =: UserInfo.getUserId() and type1__c =: '有出生' and Id not in: ExistNewBornHosId]; //get current user's hospitals
            List<Hospital__c> ChangeMsrHos = new List<Hospital__c>();
            for(Hospital__c hp:HosptialListAll)
            {
                Date BiggestDate;
                List<HospitalChangeHistory__c> HosHisList = [Select id,effectivedate__c From HospitalChangeHistory__c Where Hospital__r.id=: hp.id and Name =: '改变MSR'];   // get change msr history           
                if(HosHisList.size()>0){
                    for(HospitalChangeHistory__c hch : HosHisList) // get biggest change date
                    {
                        if(BiggestDate == null){
                            BiggestDate = hch.effectivedate__c;
                        }
                        else{
                            if(BiggestDate < hch.effectivedate__c){
                                BiggestDate = hch.effectivedate__c;
                            }
                        }
                    }
                   
                   if((IyearCom > BiggestDate.year())||((IyearCom == BiggestDate.year())&&(Imonth >= BiggestDate.month() - 1 ))){
                        if(hp.Active__c == true){
                            ChangeMsrHos.add(hp);
                            HospitalList.add(hp);  
                        }
                        
                       if((hp.effectivedate__c <= DtodayCom)&&(hp.Active__c == false))
                       {

                           HospitalList.add(hp);
                       }
                   }
                }
                else{
                    if(hp.Active__c == true){

                        HospitalList.add(hp);
                    }
                    
                   if((hp.effectivedate__c <= DtodayCom)&&(hp.Active__c == false))
                   {

                       HospitalList.add(hp);
                   }      
                            
                }

            }
            

        //create the record items       
        for(Hospital__c pl:HospitalList)       
        {
            AddMonthlyNewBornItemControl add = new AddMonthlyNewBornItemControl();
            AddMonthlyNewBornItemControl addNew = new AddMonthlyNewBornItemControl();
            Boolean jumpFlag = false;
            
            //create the record name 
            Date Dtoday = Date.today();
                        
            String RecordName = pl.Name + Syear + '年'+ Smonth + '月填报';       
            
            for(NewBornNumber__c haveRecord:haveRecordList)
            {
                if(haveRecord.Hospital__c == pl.Id){                    
                    jumpFlag = true;
                }
            }
            if(jumpFlag == true){
                continue;
            }

            addNew.NewBornNum.Hospital__c = pl.Id;
            addNew.haveRecord = false;
            addNew.NewBornNum.HospitalClass__c = String.valueOf(pl.class__c);
            addNew.NewBornNum.NewBornNum__c = 0;
            addNew.HosString = pl.name;
            RecordList.add(addNew);
        }
        for(NewBornNumber__c haveRecord: haveRecordList)
        {
            AddMonthlyNewBornItemControl addNb = new AddMonthlyNewBornItemControl();
            addNb.NewBornNum = haveRecord;
            String num = string.valueOf(haveRecord.NewBornNum__c);
            if(num != null){
                addNb.NewBornNum.NewBornNum__c = integer.valueOf(num);  
            }
            else{
                addNb.NewBornNum.NewBornNum__c = 0;
            }
            if(haveRecord.ownerid != UserInfo.getUserId())
            {
                addNb.NewBornNum.NewBornNum__c = 0;
            }             
            addNb.haveRecord = true;
            addNb.NewBornNum.HospitalClass__c = haveRecord.hospital_class__c;
            addNb.HosString = haveRecord.name.substring(0,haveRecord.name.indexOf('201'));
            RecordList.add(addNb);            
        }
        
        SaveOrNot = false;
               
        return null;
    }
 
   
    public PageReference Save()
    {
        List<NewBornNumber__c> UpdateList = new List<NewBornNumber__c>();
        List<NewBornNumber__c> InsertList = new List<NewBornNumber__c>();
        if(Overdate){
            return null;
        } 
        if(RecordList != null)
        {          
           for(AddMonthlyNewBornItemControl nbn:RecordList) //loop from item list
           {
               //create the recoed name 
               //if(nbn.NewBornNum.NewBornNum__c != 0){
                   List<Hospital__c> hNameList = [select Name from Hospital__c where Id  =: nbn.NewBornNum.Hospital__c];
                   Hospital__c hName = new Hospital__c();
                   if(hNameList.size()>0){
                       hName = hNameList[0];
                   }
                   Date Dtoday = Date.today();
    
                   String Smonth = String.valueOf(Imonth);
                   String Syear = String.valueOf(IyearCom);
                   if(hName !=null){
                       String RecordName = hName.Name + Syear + '年'+ Smonth + '月填报';     
                       nbn.NewBornNum.Name = RecordName;
                   }
                   nbn.NewBornNum.Month__c = Smonth;
                   nbn.NewBornNum.Year__c = Syear;
                   nbn.NewBornNum.NewBornNum__c = nbn.NewBornNum.NewBornNum__c; 
                    nbn.NewBornNum.ownerid = UserInfo.getUserId();
                    if(nbn.haveRecord == true){
                        UpdateList.add(nbn.NewBornNum);
                    }
                    else{
                        InsertList.add(nbn.NewBornNum);
                    }          
              // }
           } 
           if(UpdateList.size() > 0)
               Update UpdateList;
           if(InsertList.size() > 0)
           Insert InsertList;   
            //return page to home page 
            msg1 = '保存成功';
            SaveOrNot = true;
            actionSupport();           

         }
         return null;             
    }
    
    public PageReference Cancel()
    {
            pageReference pr = new pageReference('/home/home.jsp');    
            pr.setredirect(true);      
            return pr;    
    }
    
    
    
    static testMethod void AddMonthlyNewBornControlTest()
    { 
        
     
        Profile p  = [select id from profile where name =: 'System Administrator'or name =: '系统管理员'];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='standarduser111@testorg1.com');
        insert u1;
        

             
         
        System.runAs(u1) {

        Hospital__c hos = new Hospital__c();
        hos.Name = 'aaaaaaaa';
        hos.Nickname__c = 'aaaaaaaaaaa';
        hos.Active__c = true;
        hos.type1__c = '有出生';
        insert hos;
        
        HCP__c hcp= new HCP__c();
        hcp.class1__c = '全国学术带头人(NKOL)';
        hcp.Hospital__c = hos.Id;
        hcp.Active__c = true;
        insert hcp;   
        
            AddMonthlyNewBornControl testCase = new AddMonthlyNewBornControl();     
        
            System.assert(testCase.UrlId == null);
            System.assert(testCase.YearList != null);
            System.assert(testCase.MonthList != null);

            Hospital__c hos1 = new Hospital__c(Name = 'a',Active__c = true);
            hos1.OwnerId = u1.Id;
            hos1.Nickname__c = 'a';
 
            insert hos1;
              
            testCase.HospitalList = new List<Hospital__c>();
            testCase.HospitalList.add(hos1);

            AddMonthlyNewBornItemControl amnbic = new AddMonthlyNewBornItemControl();
            amnbic.NewBornNum.NewBornNum__c = 10;
            amnbic.NewBornNum.Hospital__c = hos1.Id;
            testCase.Overdate = false;
            testCase.RecordList = new List<AddMonthlyNewBornItemControl>();
            testCase.RecordList.add(amnbic);  
            testCase.actionSupport();         
            testCase.Save();  
            testCase.Cancel();                          
        }
    }        
}